package com.csw.android.ffmpegtest.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration

class ClickOrLongPressView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    var onLongPressListener: OnLongPressListener? = null
    private var dt = 0L
    private val delayLongPressEvent = object : Runnable {
        override fun run() {
            isPress = true
            onLongPressListener?.onStartPress()
        }
    }

    private var bgColor = Color.WHITE
        set(value) {
            field = value
            postInvalidate()
        }
    private val paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.color = bgColor
        canvas.drawCircle(width / 2f, height / 2f, Math.min(width, height) / 2f, paint)
    }

    private val minMoveDistance = ViewConfiguration.get(context).scaledTouchSlop
    private val maxClickSpaceTime = 200L
    private var startX: Float = 0F
    private var startY: Float = 0F
    private var isPress = false
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.run {
            when (action) {
                MotionEvent.ACTION_DOWN -> {
                    bgColor = Color.RED
                    dt = System.currentTimeMillis()
                    startX = x
                    startY = y
                    postDelayed(delayLongPressEvent, maxClickSpaceTime)
                    isPress = false
                }
                MotionEvent.ACTION_MOVE -> {
                    if (Math.abs(x - startX) > minMoveDistance || Math.abs(y - startY) > minMoveDistance) {
                        //is moving
                        if (!isPress) {
                            removeCallbacks(delayLongPressEvent)
                            isPress = true
                            onLongPressListener?.onStartPress()
                        } else {

                        }
                    } else {

                    }
                }
                MotionEvent.ACTION_UP -> {
                    bgColor = Color.WHITE
                    removeCallbacks(delayLongPressEvent)
                    if (isPress) {
                        onLongPressListener?.onEndPress()
                    } else {
                        performClick()
                    }
                }
                else -> {
                }
            }
        }
        return true
    }

    interface OnLongPressListener {
        fun onStartPress()
        fun onEndPress()
    }
}